<script lang="ts" setup>
import { ref } from 'vue';
import { useAppStore } from '@/home/stores/app';
import { useFetch } from '@/home/hooks/fetch';
import { useAsyncData } from '@/home/hooks/async-data';
import { STORAGE_KEY_HOME_POPUP } from '@/common/utils/constants';
import Template1 from '@/common/components/popup-template/pc/template1.vue';
import Template2 from '@/common/components/popup-template/pc/template2.vue';

const { $fetch } = useFetch();
const appStore = useAppStore();
const userInfo = appStore.user;
const isShowPopup = ref(false)
// 有效期，单位：秒
const POPUP_EXPIRES = 60 * 60 * 6;

const { data: popData } = useAsyncData(
  'home:popup:data',
  async () => {
    const results = await Promise.all([
      $fetch('/popup/info'),
      userInfo.id && $fetch('/user/isMembers'),
    ]);

    return {
      isSuccess: true,
      data: {
        popup: results[0].data,
        isMember: results[1]?.data,
      },
    }
  },
  {
    onAfterHandle() {
      if (!import.meta.env.SSR) {
        const { upType } = popData.value.popup;
        const { isMember } = popData.value;

        if ((upType === 1 && !isMember && isExpires()) || (upType === 2 && isExpires())) {
          isShowPopup.value = true;
        }
      }
    },
  },
);

// 显示弹窗是否过期
const isExpires = () => {
  const data = JSON.parse(localStorage.getItem(STORAGE_KEY_HOME_POPUP) ?? '{}') || {};
  const now = new Date().getTime();

  if (data.time) {
    const time = Number(data.time);

    if (!isNaN(time)) {
      if (now - time <= POPUP_EXPIRES * 1000) {
        // 没过期
        return false;
      }
    }
    else {
      // time 值非法，认为过期了
    }
  }

  data.time = now;

  localStorage.setItem(STORAGE_KEY_HOME_POPUP, JSON.stringify(data));

  // 默认认为已过期
  return true;
};

const joinCommunity = async (refreshPage: boolean = false) => {
  const { isSuccess } = await $fetch('/user/joinCommunity', {
    autoGotoLogin: true,
  });

  if (isSuccess) {
    console.log('success');
    if (refreshPage) {
      window.location.reload();
    }
  } else {
    console.log('fail');
  }
};
</script>

<template>
  <section class="page-home-popup-card">
    <ClientOnly>
      <template v-if="isShowPopup">
        <template v-if="popData?.popup?.upType === 1 ">
          <div class="fixed left-50% top-20% z-99999 translate-x--50%">
            <Template1 :title="popData.popup.title" :des="popData.popup.content" :pic="popData.popup.pic" @join="joinCommunity" @close="isShowPopup = false" />
          </div>
        </template>
        <template v-else-if="popData?.popup?.upType === 2">
          <div class="fixed left-50% top-20% z-99999 translate-x--50%">
            <Template2 :link="popData.popup.content" :des="popData.popup.title" :pic="popData.popup.pic" @close="isShowPopup = false" />
          </div>
        </template>
      </template>
    </ClientOnly>
  </section>
</template>

<style lang="scss" scoped>
</style>
